<?php

namespace App\Http\Controllers\Profile;

use App\Http\Controllers\Controller;
use App\Repositories\Contracts\AttachmentRepositoryInterface;
use App\Repositories\Contracts\UserRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class ProfileController extends Controller {
  /**
   * @var UserRepositoryInterface serRepositoryInterface
   */
  private $userRepository;
  private $attachmentRepository;

  /**
   * UserController constructor.
   *
   * @param UserRepositoryInterface $userRepository
   * @param AttachmentRepositoryInterface $attachmentRepository
   */
  public function __construct( UserRepositoryInterface $userRepository, AttachmentRepositoryInterface $attachmentRepository ) {
    $this->userRepository       = $userRepository;
    $this->attachmentRepository = $attachmentRepository;
  }


  /**
   * @param Request $request
   *
   * @return \Illuminate\Http\JsonResponse
   */
  public function changePassword( Request $request ) {
    $user = Auth::user();
    $data = $request->only( 'id', 'old_password', 'password', 'password_confirmation' );
    $this->validateChangePassword( $data, $user )->validate();
    $result = $this->userRepository->changePassword( $data['id'], $data['password'] );

    return $this->result( $result );
  }

  /**
   * @param $data
   *
   * @return \Illuminate\Contracts\Validation\Validator
   */
  public function validateChangePassword( $data, $user ) {

    $roles = [
      'id'           => [ 'eq:' . $user->id ],
      'old_password' => [ 'required', 'password:' . $user->password ],
      'password'     => [ 'required', 'string', 'min:6', 'max:255', 'confirmed' ]
    ];

    return Validator::make( $data, $roles );
  }


  public function avatar( Request $request ) {
    $result = $this->attachmentRepository->upload( $request->file( 'avatar' ) );
    if ( ! $result ) {
      return $this->result( false );
    }
    $userId  = Auth::id();
    $attachmentId = $result[0]['id'];
    $user=$this->userRepository->setAvatar($userId,$attachmentId);
    return $this->result( true,$user);
  }
}
